import * as apiUser from '@/api/apiUser.js'
import * as _token from '@/utils/_token'
import isEmpty from 'lodash/isEmpty'


const getDefaultState = () => {
	return {
		isLoggedIn: !isEmpty(_token.getToken()),
		user: _token.getUser(),
		accessToken: _token.getToken(),
		accessTokenExpiredAt: _token.getTokenExpiredAt(),
	}
}

// 定义 state
const state = getDefaultState();


// 定义 getters
let getters = {
	isLoggedIn: state => state.isLoggedIn,
	user: state => state.user,
	accessToken: state => state.accessToken,
	accessTokenExpiredAt: state => state.accessTokenExpiredAt
}

// 定义 actions
const actions = {
	async login({state, commit}, params = {}) {
		let result = await apiUser.login(params)
		if (result.statusCode == 200){
			// 设置token
			commit('setToken', result.data)
			_token.setToken(result.data)
			// 设置登陆状态
			state.isLoggedIn = true
			// 设置用户
			commit('setUser', params.userInfo)
			_token.setUser(params.userInfo)
		}
		return result;
	},
	// 设置刷新后的TOKEN
	async refreToken({state, commit}, token = {}){
		let refreRsult = await apiUser.refreToken(state.accessToken)

		if (refreRsult.statusCode == 200){
			// 设置token
			commit('setToken', refreRsult.data)
			_token.setToken(refreRsult.data)
		}
	},
	// 获取用户数据
	async getUser({state, commit}) {
		const userResult = await apiUser.getCurrentUser({
			url: '/user'
		})
		console.log(userResult)
		commit('setUser', userResult.data)
		_token.setUser(userResult.data)
	},
	// 退出登陆
	logout({state, commit, getters}) {
		// 退出登陆
		_token.logout()
		uni.showToast({
			title: '退出登陆...',
			icon: 'loading',
			duration:1000,
			success: (result) => {
				setTimeout(()=>{
					if(!result){
						uni.showModal({
							title: '提示',
							content: '网络异常',
							showCancel:false
						})
					}else{
						uni.showToast({
						    title: '退出成功',
						    duration: 1000
						});
						state.user.nickName = '未登陆'
						state.user.avatarUrl = '/static/images/user/avatar.jpg'
						state.isLoggedIn = false
					}
				},1000)
			}
		})
	},
}


// 定义 mutations
const mutations = {
	setUser(state, user) {
		
		state.user = user
	},
	setToken(state, tokenPayload) {
		state.accessToken = tokenPayload.access_token
		state.accessTokenExpiredAt = new Date().getTime() + tokenPayload.expired_at * 1000
	}
}

/**
 * 把内容暴露出去
 */
export default {
	state,
	getters,
	actions,
	mutations
}